" This code sets shortcuts for close buffer and save.
" They both work to let you know when a file has unsaved changes
" and offers you to give it a filename. We take this granted on
" modern text editors, but VIM does not have it by default.
" Tested in NeoVim, but should work with VIM as well.
" Put this on your ~/.vimrc for VIM and ~/.config/nvim/init.vim for
" neovim.
" Remaps 2 keyboard shortcuts
" Ctrl+W: for closing the buffer (and ask for confirmation, filename etc.)
" Ctrl+S: save (and ask for filename if not already saved
" A "Save As" feature can also be built from this code if you want!

" -- save related -- "
function! SaveFile()
	let old_name = expand('%')
	if old_name != ''
		exec ':w'
	else
		let filename_input = input('Enter filename to save as: ')
		exec ':saveas ' . filename_input
	endif
endfunction
nnoremap <C-s> :call SaveFile()<cr>
inoremap <C-s> <Esc>:call SaveFile()<cr>i
vnoremap <C-s> <Esc>:call SaveFile()<cr>v

" -- close buffer related -- "
function! CloseFile()
	let old_name = expand('%')
	let unsaved_changes = &mod
	if unsaved_changes == 1
		" there are unsaved changes, so we offer to save
		let savechanges_input = input('Do you want to save changes? (y/n) ')
		if savechanges_input == 'y'
			:call SaveFile()
		endif
	endif
	exec ':q!'
	redraw!
endfunction
nnoremap <C-w> :call CloseFile()<cr>
inoremap <C-w> <Esc>:call CloseFile()<cr>
vnoremap <C-w> <Esc>:call CloseFile()<cr>
